﻿/*
 *  WebRequestHelper 17/7/13
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AcfunUpload
{
    public static class WebRequestHelper
    {
        private static string contenttype = "application/x-www-form-urlencoded";
        private static string useragent = "BoomFun";
        private static int timeout = 10000;
        /// <summary>
        /// 获取或设置全局content-type,默认为application/x-www-form-urlencoded
        /// </summary>
        public static string Contenttype
        {
            get
            {
                return contenttype;
            }
            set
            {
                contenttype = value;
            }
        }
        /// <summary>
        /// 获取或设置全局useragent,默认为BoomFun
        /// </summary>
        public static string Useragent
        {
            get
            {
                return useragent;
            }
            set
            {
                useragent = value;
            }
        }
        /// <summary>
        /// 获取或设置全局timeout,默认为10000(ms)
        /// </summary>
        public static int Timeout
        {
            get
            {
                return timeout;
            }
            set
            {
                timeout = value;
            }
        }
        /// <summary>
        /// GET网页请求
        /// </summary>
        /// <param name="url">请求网址</param>
        /// <returns></returns>
        public static string http(string url)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Timeout = timeout;
                hw.Proxy = null;
                hw.Method = "GET";
                hw.ContentType = contenttype;
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        ///  GET网页请求
        /// </summary>
        /// <param name="url">请求网址</param>
        /// <param name="proxy">代理地址</param>
        /// <returns></returns>
        public static string http(string url, string proxy)
        {
            HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
            hw.Proxy = new WebProxy(proxy, true);
            hw.Timeout = timeout;
            hw.Method = "GET";
            hw.ContentType = contenttype;
            HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
            StreamReader sr = new StreamReader(hwr.GetResponseStream());
            return sr.ReadToEnd();
        }
        /// <summary>
        /// GET网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="gbk">是否GBK编码</param>
        /// <returns></returns>
        public static string http(string url, bool gbk)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Proxy = null;
                hw.Timeout = timeout;
                hw.Method = "GET";
                hw.ContentType = contenttype;
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                if (gbk)
                {
                    StreamReader sr = new StreamReader(hwr.GetResponseStream(), Encoding.GetEncoding("gbk"));
                    return sr.ReadToEnd();
                }
                else
                {
                    StreamReader sr = new StreamReader(hwr.GetResponseStream());
                    return sr.ReadToEnd();
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// GET网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="gbk">是否GBK编码</param>
        /// <returns></returns>
        public static string http(string url, bool mobile, string ua)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Proxy = null;
                hw.Timeout = timeout;
                hw.Method = "GET";
                hw.UserAgent = ua;
                hw.ContentType = contenttype;
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">类型，POST为1</param>
        /// <param name="postdata">发送数据（GET请求发空）</param>
        /// <returns></returns>
        public static string http(string url, int type, string postdata)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Timeout = timeout;
                hw.Proxy = null;
                byte[] PD = Encoding.UTF8.GetBytes(postdata);
                if (type == 1)
                {
                    hw.Method = "POST";
                }
                else
                {
                    hw.Method = "GET";
                }
                hw.ContentType = contenttype;
                if (type == 1)
                {
                    Stream Stream = hw.GetRequestStream();
                    Stream.Write(PD, 0, PD.Length);
                    Stream.Close();
                }
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">类型，POST为1</param>
        /// <param name="postdata">发送数据（GET请求发空）</param>
        /// <param name="proxy">代理</param>
        /// <returns></returns>
        public static string http(string url, int type, string postdata, string proxy)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Timeout = timeout;
                hw.Proxy = new WebProxy(proxy, true);
                byte[] PD = Encoding.UTF8.GetBytes(postdata);
                if (type == 1)
                {
                    hw.Method = "POST";
                }
                else
                {
                    hw.Method = "GET";
                }
                hw.ContentType = contenttype;
                if (type == 1)
                {
                    Stream Stream = hw.GetRequestStream();
                    Stream.Write(PD, 0, PD.Length);
                    Stream.Close();
                }
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">类型，POST为1</param>
        /// <param name="postdata">发送数据（GET请求发空）</param>
        /// <param name="cc">ref返回cookie</param>
        /// <returns></returns>
        public static string http(string url, int type, string postdata, ref CookieContainer cc)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Proxy = null;
                hw.Timeout = timeout;
                hw.CookieContainer = cc;
                byte[] PD = Encoding.UTF8.GetBytes(postdata);
                if (type == 1)
                {
                    hw.Method = "POST";
                }
                else
                {
                    hw.Method = "GET";
                }
                hw.ContentType = contenttype;
                if (type == 1)
                {
                    Stream Stream = hw.GetRequestStream();
                    Stream.Write(PD, 0, PD.Length);
                    Stream.Close();
                }
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">类型，POST为1</param>
        /// <param name="gbk">是否GBK编码</param>
        /// <param name="postdata"></param>
        /// <param name="cc"></param>
        /// <returns></returns>
        public static string http(string url, int type, bool gbk, string postdata, ref CookieContainer cc)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Proxy = null;
                hw.Timeout = timeout;
                hw.CookieContainer = cc;
                byte[] PD = Encoding.UTF8.GetBytes(postdata);
                if (type == 1)
                {
                    hw.Method = "POST";
                }
                else
                {
                    hw.Method = "GET";
                }
                hw.ContentType = contenttype;
                if (type == 1)
                {
                    Stream Stream = hw.GetRequestStream();
                    Stream.Write(PD, 0, PD.Length);
                    Stream.Close();
                }
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                if (gbk)
                {
                    StreamReader sr = new StreamReader(hwr.GetResponseStream(), Encoding.GetEncoding("gbk"));
                    return sr.ReadToEnd();
                }
                else
                {
                    StreamReader sr = new StreamReader(hwr.GetResponseStream());
                    return sr.ReadToEnd();
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 网页请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">类型，POST为1</param>
        /// <param name="postdata">发送数据（GET请求发空）</param>
        /// <param name="proxy">代理</param>
        /// <param name="cc">ref返回cookie</param>
        /// <returns></returns>
        public static string http(string url, int type, string postdata, string proxy, ref CookieContainer cc)
        {
            try
            {
                HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(url);
                hw.Timeout = timeout;
                hw.Proxy = new WebProxy(proxy, true);
                hw.CookieContainer = cc;
                byte[] PD = Encoding.UTF8.GetBytes(postdata);
                if (type == 1)
                {
                    hw.Method = "POST";
                }
                else
                {
                    hw.Method = "GET";
                }
                hw.ContentType = contenttype;
                if (type == 1)
                {
                    Stream Stream = hw.GetRequestStream();
                    Stream.Write(PD, 0, PD.Length);
                    Stream.Close();
                }
                HttpWebResponse hwr = (HttpWebResponse)hw.GetResponse();
                StreamReader sr = new StreamReader(hwr.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }
        public static string uploadPic(byte[] pic,string ext,string token)
        {
            long timestamp = Utils.getTimestamp();
            string contentType = (ext==".jpg" || ext == ".jpeg")?"image/jpeg": "image/png";
            string before = "---------------------------99531436059624"+
                            "Content-Disposition: form-data; name=\"name\""+
                            "\r\n"+
                            "content/2017_07_19/1500458938.jpg" +
                            "---------------------------99531436059624" +
                            "Content-Disposition: form-data; name=\"chunk\""+
                            "\r\n" +
                            "0" +
                            "---------------------------99531436059624"+
                            "Content -Disposition: form-data; name=\"chunks\""+
                            "\r\n" +
                            "1" +
                            "---------------------------99531436059624" +
                            "Content-Disposition: form-data; name=\"key\""+
                            "\r\n"+
                            "content/" + DateTime.Now.Year + "_" + DateTime.Now.Month+ "_" + DateTime.Now.Day + "/"+ timestamp +ext +
                            "---------------------------99531436059624" +
                            "Content-Disposition: form-data; name=\"token\""+
                            "\r\n"+
                            token +
                            "---------------------------99531436059624" +
                            "Content-Disposition: form-data; name=\"file\"; filename=\"content/" + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "/" + timestamp +ext+"\""+
                            "Content-Type: "+contentType;
            string after = "-----------------------------ei4cH2KM7gL6cH2ae0Ij5cH2cH2gL6";
            HttpWebRequest request = WebRequest.Create("http://upload.qiniu.com/") as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = "---------------------------99531436059624"; // 随机分隔线
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes(before);
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(after);
            byte[] bArr = pic;

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(response.GetResponseStream());
            return sr.ReadToEnd();
        }
    }
}
